﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace CPPEI.WebApi
{
    /// <summary>
    /// 存放认证信息（使用cookie）
    /// </summary>
    public class CookieAuthProvider : IAuthProvider
    {
        public bool Save(string userId, TimeSpan expires)
        {
            string token = Guid.NewGuid().ToString("N");
            HttpResponse response = HttpContext.Current.Response;

            HttpCookie cookie = new HttpCookie("webapi_auth");//初使化并设置Cookie的名称
            DateTime dt = DateTime.Now;
            cookie.Expires = dt.Add(expires);//设置过期时间
            cookie.Values.Add("userid", userId);
            cookie.Values.Add("token", token);
            response.AppendCookie(cookie);
            return true;
        }

        public void Delete()
        {
            HttpRequest request = HttpContext.Current.Request;
            HttpResponse response = HttpContext.Current.Response;
            if (request.Cookies["webapi_auth"] != null)
            {
                TimeSpan ts = new TimeSpan(-1, 0, 0, 0);
                request.Cookies["webapi_auth"].Expires = DateTime.Now.Add(ts);//删除整个Cookie，只要把过期时间设置为现在
                response.AppendCookie(request.Cookies["webapi_auth"]);
            }
        }

        public string GetUserId()
        {
            HttpRequest request = HttpContext.Current.Request;
            if (request.Cookies["webapi_auth"] != null)
            {
                return request.Cookies["webapi_auth"]["userid"];
            }
            return null;
        }

        public string GetToken()
        {
            HttpRequest request = HttpContext.Current.Request;
            if (request.Cookies["webapi_auth"] != null)
            {
                return request.Cookies["webapi_auth"]["token"];
            }
            return null;
        }

        public  bool IsAuth()
        {
            HttpRequest request = HttpContext.Current.Request;
            if (request.Cookies["webapi_auth"] != null)
            {
                return true;
            }
            return false;
        }
    }
}
